<script setup>
import PageContainer from '@/components/PageContainer/index.vue'
import appTable from '@/components/i-table/t-able.vue'
import mySelect from './components/ChannelSelect.vue'
import { artGetListService, artDelService } from '@/api/article'
import { formatTime } from '@/utils/format'
import ArticleEdit from './components/ArticleEdit.vue'
import { reactive, ref, markRaw, onMounted, resolveComponent, h } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
const articleEditRef = ref()

onMounted(() => {
  getList()
})

const getList = async () => {
  let params = Object.assign({}, queryParams, tableContent.pagination)
  console.log(tableContent.pagination, params)
  tableContent.options.loading = true
  const res = await artGetListService(params)
  tableContent.list = res.data.data
  tableContent.total = res.data.total
  tableContent.options.loading = false
}
const onDetails = (row) => {
  console.log(row)
  articleEditRef.value.open(row, true)
}
// 切换每页显示的数量
const handleSizeChange = (pagination) => {
  console.log('pagination', pagination)
  Object.assign(tableContent.pagination, pagination)
  getList()
}
// 切换页码
const handleIndexChange = (pagination) => {
  console.log('pagination', pagination)
  tableContent.pagination = pagination
  getList()
}
const onAddArticle = () => {
  articleEditRef.value.open({})
}
const onEditArticle = (row) => {
  console.log(row)
  articleEditRef.value.open(row)
}
const onDeleteArticle = async (row) => {
  await ElMessageBox.confirm('你确认删除该文章信息吗？', '温馨提示', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  })
  await artDelService(row.id)
  ElMessage({ type: 'success', message: '删除成功' })
  getList()
}

const handleQuery = () => {
  Object.assign(tableContent.pagination, { pagenum: 1, pagesize: 10 })
  getList()
}
const resetQuery = () => {
  try {
    formRenderer.value.resetFields()
    console.log('组件内删除逻辑', queryParams)
    getList()
  } catch (error) {
    console.log(error)
  }
}
// 表格
let tableContent = reactive({
  total: 0,
  list: [],
  otherHeight: 150,
  columns: [
    {
      prop: 'link',
      align: 'center',
      label: '',
      width: '160',
      render: ({ row }) => {
        return h(
          // 按名称手动解析已注册的组件。
          resolveComponent('el-link'),
          {
            type: 'primary',
            underline: false,
            onClick: () => {
              onDetails(row)
              console.log(row)
            }
          },
          () => row.title
        )
      }
    },
    {
      prop: 'cate_name',
      label: '分类',
      align: 'center'
    },
    {
      prop: 'pub_date',
      label: '发表时间',
      align: 'center',
      formatter: (row) => {
        return formatTime(row.pub_date)
      }
    },
    {
      prop: 'state',
      label: '状态',
      align: 'center'
    }
  ], // 需要展示的列
  options: {
    stripe: true, // 是否为斑马纹 table
    loading: false, // 是否添加表格loading加载动画
    highlightCurrentRow: true, // 是否支持当前行高亮显示
    mutiSelect: false, // 是否支持列表项选中功能
    border: true, //是否显示边框
    numbers: true //是否显示序号
  }, // table 的参数
  pagination: {
    pageSizes: [2, 4, 6, 8],
    pagenum: 1,
    pagesize: 10
  }, // 分页参数
  operates: {
    width: 200,
    list: [
      {
        label: '编辑',
        type: 'primary',
        plain: true,
        icon: 'Edit',
        method: (index, row) => {
          onEditArticle(row)
          console.log('编辑')
        }
      },
      {
        label: '删除',
        type: 'danger',
        icon: 'Delete',
        plain: true,
        method: (index, row) => {
          onDeleteArticle(row)
          console.log('删除')
        }
      }
    ]
  }
})
const queryParams = reactive({ state: '已发布' })
const formRenderer = ref()
const content = reactive([
  {
    type: 'select',
    id: 'cate_id',
    label: '文章分类',
    component: markRaw(mySelect)
  },
  {
    type: 'select',
    id: 'state',
    label: '发布状态',
    options: [
      {
        label: '已发布',
        value: '已发布'
      },
      {
        label: '草稿',
        value: '草稿'
      }
    ]
  }
])
// 添加修改成功
const onSuccess = (type) => {
  if (type === 'add') {
    // 如果是添加，需要跳转渲染最后一页，编辑直接渲染当前页
    const lastPage = Math.ceil(
      (tableContent.total + 1) / tableContent.pagination.pagesize
    )
    tableContent.pagination.pagenum = lastPage
  }
  getList()
}
</script>
<template>
  <page-container title="文章管理">
    <template #extra>
      <el-button type="primary" @click="onAddArticle">发布文章</el-button>
    </template>
    <el-form-renderer
      label-width="100px"
      :content="content"
      ref="formRenderer"
      style="padding-right: 30px"
      v-model:FormData="queryParams"
      class="render-form"
    >
      <el-button type="primary" @click="handleQuery">搜索</el-button>
      <el-button @click="resetQuery"> 重置 </el-button>
    </el-form-renderer>

    <app-table
      :list="tableContent.list"
      :total="tableContent.total"
      :otherHeight="tableContent.otherHeight"
      :options="tableContent.options"
      :pagination="tableContent.pagination"
      :columns="tableContent.columns"
      :operates="tableContent.operates"
      @handleSizeChange="handleSizeChange"
      @handleIndexChange="handleIndexChange"
    >
    </app-table>
  </page-container>
  <!-- 弹窗 -->
  <article-edit ref="articleEditRef" @success="onSuccess"></article-edit>
</template>
<style scoped></style>
